using System;
using System.Collections.Generic;
using System.Text;

namespace Emlyn.Common.Tools.Web
{
    public class UriBuilder2: UriBuilder
    {
        private QueryDictionary _query2;

        private void temp()
        {
            UriBuilder lb = new UriBuilder();
        }

        public UriBuilder2()
            : base() 
        {
            InitQuery2();
        }

        public UriBuilder2(string uri)
            : base(uri) 
        {
            InitQuery2();
        }

        public UriBuilder2(Uri uri)
            : base(uri)
        {
            InitQuery2();
        }

        public UriBuilder2(string schemeName, string hostName)
            : base(schemeName, hostName) 
        {
            InitQuery2();
        }

        public UriBuilder2(string scheme, string host, int portNumber)
            : base(scheme, host, portNumber) 
        {
            InitQuery2();
        }

        public UriBuilder2(string scheme, string host, int portNumber, string pathValue)
            : base(scheme, host, portNumber, pathValue) 
        {
            InitQuery2();
        }

        public UriBuilder2(string scheme, string host, int port, string path, string extraValue)
            : base(scheme, host, port, path, extraValue) 
        {
            InitQuery2();
        }

        private void InitQuery2()
        {
            _query2 = new QueryDictionary(Query);
            _query2.Change = new DictionaryChange(OnQuery2Change);
        }

        private void OnQuery2Change()
        {
            Query = _query2.GetQueryString();
            InitQuery2();
        }

        public QueryDictionary Query2
        {
            get { return _query2; }
        }

        public Uri Uri2
        {
            get
            {
                return GetUri2();
            }
        }

        protected virtual Uri GetUri2()
        {
            Uri retval = null;

            if (_query2.GetQueryString() != Query)
                InitQuery2();

            retval = Uri;

            return retval;
        }

        public static Uri RemoveQueryItem(Uri luri, string lkey)
        {
            UriBuilder2 lbuilder = new UriBuilder2(luri);

            lbuilder.Query2.Remove(lkey);

            return lbuilder.Uri2;
        }

        public static Uri AddQueryItem(Uri luri, string lkey, string lvalue)
        {
            UriBuilder2 lbuilder = new UriBuilder2(luri);

            lbuilder.Query2[lkey] = lvalue;

            return lbuilder.Uri2;
        }
    }
}
